﻿using MessageQueues.MSMQ.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace MessageQueues.MSMQ.Implement
{
    /// <summary>
    /// 消息队列控制器
    /// </summary>
    public partial class MessageQueueHandler : IMessageQueueMethod
    {
        /// <summary>
        /// 创建队列
        /// </summary>
        /// <param name="type">队列类型(默认是专用队列)</param>
        /// <returns>队列对象</returns>
        public MessageQueue Create(QueueType type = QueueType.PrivateQueue)
        {
            MessageQueue queue = default(MessageQueue);
            try
            {
                queue = MessageQueue.Create(setting.MessageQueuePath, setting.IsUseTransaction);
            }
            catch (Exception)
            {

                throw; new Exception("创建队列时出错");
            }
            return queue;
        }

        /// <summary>
        /// 删除队列
        /// </summary>
        public void Delete()
        {
            try
            {
                MessageQueue.Delete(setting.MessageQueuePath);
            }
            catch (Exception)
            {

                throw; new Exception("删除队列时出错");
            }
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            try
            {
                queue?.Close();
            }
            catch (Exception)
            {
                throw; new Exception("释放资源时出错");
            }
            GC.SuppressFinalize(this);
        }

        ~MessageQueueHandler()
        {
            Dispose();
        }

        /// <summary>
        /// 验证队列是否存在
        /// </summary>        
        /// <returns>验证结果</returns>
        public bool Exists()
        {
            var successed = false;
            try
            {
                successed = MessageQueue.Exists(setting.MessageQueuePath);
            }
            catch (Exception)
            {
                throw new Exception("验证队列是否存在时出错");
            }
            return successed;
        }
    }
}
